<?php
/**
 * 企业团检申请
 *
 * User: kaikaic
 * Date: 2018/11/24
 * Time: 12:51
 */

namespace app\exam\service;

use service\BasicService;
use service\ToolsService;
use think\Db;

class GroupApplyService extends BasicService {

    public function init() {
        $this->dataTable = ['ExamGroupApply'];
    }

    /**
     * 如果有一个已经提交，处于待审核状态的申请，则不能继续提交
     *
     * @param $contacts
     * @param $contactNumber
     * @return array|null
     */
    public function haveApply($contacts, $contactNumber) {
        $condition = array();
        $condition['contacts'] = $contacts;
        $condition['contact_number'] = $contactNumber;
        $condition['status'] = 1;

        return $this->single($condition);
    }

    /**
     * 初始化团检信息
     */
    public function initGroup($applyID) {
        $apply = $this->find($applyID);
        if (!$apply) {
            return false;
        }

        $enterpriseID = $this->initEnterprise($apply);
        if (!$enterpriseID) {
            return false;
        }

        return $this->initGroupPlan($apply, $enterpriseID);
    }

    /**
     * 初始化团检计划
     */
    private function initGroupPlan($apply, $enterpriseID) {
        $data = array();

        $data['title'] = $apply['name'] . "体检计划[" . date('Ymd') . "]";
        $data['enterprise_id'] = $enterpriseID;
        $data['mec_id'] = 0;
        $data['group_set_id'] = 0;
        $data['start_date'] = date("Y-m-d");
        $data['end_date'] = date("Y-m-d", strtotime("+1 month"));
        $data['comment'] = "";

        $data['status'] = 1;
        $data['create_time'] = time();

        return GroupService::getInstance()->insert($data);
    }

    /**
     * 初始化企业信息
     */
    private function initEnterprise($apply) {
        $data = array();

        $data['name'] = $apply['name'];
        $data['address'] = "";
        $data['contacts'] = $apply['contacts'];
        $data['contact_number'] = $apply['contact_number'];
        $data['abbr'] = ToolsService::getStringSpell($data['name']);

        $data['sort'] = 0;
        $data['status'] = 1;
        $data['create_time'] = time();

        return EnterpriseService::getInstance()->insert($data);
    }

}